﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBullet : Bullet
{

	// 子弹初始坐标
	private static Vector2[] iniPos = {
		new Vector2(0.8f, -0.3f),
		new Vector2(0.7f, -1f),
		new Vector2(0.8f, 0.65f),
		new Vector2(-0.2f, -1.2f),
		new Vector2(-0.1f, 1.1f),
	};

	// 子弹初始旋转角度
	private static Vector3[] iniRot = {
		new Vector3(0, 0, -90),
		new Vector3(0, 0, -135),
		new Vector3(0, 0, -45),
		new Vector3(0, 0, -180),
		new Vector3(0, 0, 0),
	};

	// 子弹运动方向
	private static Vector3[] dirs = {
		new Vector3(1, 0, 0),
		new Vector3(1, -1, 0),
		new Vector3(1, 1, 0),
		new Vector3(0, -1, 0),
		new Vector3(0, 1, 0),

		new Vector3(-1, 0, 0),
		new Vector3(-1, -1, 0),
		new Vector3(-1, 1, 0),
	};

	int dirShoot;
	private float speed = 8;
	private void Start() {
		bullet = GetComponent<Collider2D>();
		shooter = transform.parent.GetComponent<Role>();
		SetIniAttributes(this.shooter);
		StartCoroutine(AudoDestroy(5));// 5秒后自动销毁
	}

	private void Update() {
		// 沿dirShoot方向射击
		transform.localPosition += (dirs[dirShoot].normalized * Time.deltaTime * speed);
	}

	public override void SetIniAttributes(Role shooter) {
		// base.SetIniAttributes(shooter);
		this.attack = shooter.Attack * 2;       // 射击伤害为普攻两倍

		Player player = shooter as Player;
		int dir = (int)player.Dir;
		transform.localPosition = iniPos[dir % 5];
		transform.localEulerAngles = iniRot[dir % 5];
		dirShoot = dir;
		transform.parent = null;
	}

	private void OnCollisionEnter2D(Collision2D other) {
		if (other.gameObject.tag == "Floor" || other.gameObject.tag == "Wall") {
			Debug.Log("击中Floor");
			OnDestroyBullet();
		} else if (other.gameObject.tag == "Block") {
			StartCoroutine(AudoDestroy(0.3f));  // 提供0.3秒作用力后销毁
		} else if (other.gameObject.tag == "Player") {
			OnDestroyBullet();
		}
	}

	private IEnumerator AudoDestroy(float time) {
		yield return new WaitForSeconds(time);
		OnDestroyBullet();
	}

}
